import request from './request.js'

//base64传图
const uploadConfigBase64 = data => {
  return request.post('/common/UpBase64/GetUpBase64Url', data)
}

// 请求后端接口，获取上传需要的配置
// type:文件格式，如果type有值代表上传文件，否知代表上传图片
const getUploadConfig = async ({ filePath }, type) => {
  // 请求又拍云的参数配置
  let options = {}

  // 获取上传之前需要的配置信息
  const res = type ? await request.post('/bussiness/Common/UploadReceiptFileUpyunConfig',{Suffix: type}) : await request.post('/bussiness/Common/UploadAuthImgUpyunConfig')

  // 将信息配置到请求又拍云的参数上
  options.url = res.data.host
  options.formData = {
    authorization: res.data.auth,
    policy: res.data.policy
  }
  options.filePath = filePath
  options.name = 'file'

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      ...options,
      success: r => {
        let data = JSON.parse(r.data)
        if (r.statusCode === 200) {
          // let resFile =   // 把图片前面的域名加上
          resolve({ ...data, baseUrl: res.data.domain })
        } else {
          reject(err)
        }
      },
      fail: err => {
        uni.showToast({
          title: '上传失败, 请重新上传',
          duration: 2000
        })
        reject(err)
      }
    })
  })
}

//

const files = {
  //获取图片上传配置
  uploadImg(data) {
    return getUploadConfig(data)
  },
  uploadConfigBase64,
  // 获取文件上传配置
  uploadFile(data, type) {
    return getUploadConfig(data, type)
  },
}

export default files